﻿

using System;
using System.IO;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using RoboRallyAPI;

namespace RoboRally
{
    class IronPythonEngine
    {

        ScriptEngine _engine;
        ScriptRuntime _runtime;
 
        public IronPythonEngine()
        {
            _engine = Python.CreateEngine();
            _runtime = _engine.Runtime;

            _runtime.LoadAssembly(typeof(IPlayer).Assembly);
            _runtime.LoadAssembly(typeof(String).Assembly);
            _runtime.LoadAssembly(typeof(Uri).Assembly);
        }

        public IPlayer Execute(string path)
        {
            string directoryName = Path.GetDirectoryName(path);
            string stdlibDirectory = Path.Combine(new string[] { directoryName, "Lib" });

            // add script directory and Lib subdirectory to sys.path for embedded engine
            var searchPaths = _engine.GetSearchPaths();
            searchPaths.Add(directoryName);
            searchPaths.Add(stdlibDirectory);
            _engine.SetSearchPaths(searchPaths);
            
            ScriptSource script = _engine.CreateScriptSourceFromFile(path);
            ScriptScope scope = _engine.CreateScope();
            script.Execute(scope);

            ScriptSource instantiate = _engine.CreateScriptSourceFromString("_instance_ = MyPlayerBrain()");
            instantiate.Execute(scope);

            return scope.GetVariable<IPlayer>("_instance_");
        }
    }
}
